package com.yantong.controller.assets;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.yantong.constant.BalanceLogStyle;
import com.yantong.controller.BaseController;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.pojo.BalanceLog;
import com.yantong.service.BalanceService;
import com.yantong.pojo.BalanceCWLog;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 余额流水
 *
 * @author kanghaixin
 * @date 2018/9/19.10:16
 */
@Controller
@RequestMapping("/flow/balance")
public class BalanceFlowController extends BaseController {
    private static final String prefix = "flow/balance";
    @Autowired
    private BalanceService balanceService;

    private static Logger logger = LoggerFactory.getLogger(BalanceFlowController.class);

    /**
     * 余额流水页面
     *
     * @param model
     * @return
     */
    @GetMapping()
    @RequiresPermissions("flow:balance:balance")
    public String balanceFlow(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        model.addAttribute("balanceLogStyles", BalanceLogStyle.getBalanceLogStyles());
        return prefix + "/balanceFlow";
    }

    /**
     * 供应商财务余额流水
     *
     * @param model
     * @return
     */
    @GetMapping("/supplyCwBalance")
    @RequiresPermissions("flow:balance:gyscw")
    public String supplyCwBalance(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/supplyCwBalance";
    }

    /**
     * 供应商财务余额流水列表
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param source
     * @param flowtype
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/gyscwlist")
    @RequiresPermissions("flow:balance:gyscw")
    public PageUtils<BalanceCWLog> supplyCwBalanceLogs(Long centreId, Date start, Date end, Integer style,
                                                       String queryItem, String realname, String mobile, String nickname, String flowtype, int offset, int limit) {
        return balanceService.listSupplyCwBalanceLogs(centreId, start, end, style, queryItem, realname, mobile, nickname, flowtype, offset, limit);
    }

    /**
     * 余额流水记录
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("flow:balance:balance")
    public PageUtils<BalanceLog> listBalanceLogs(Long centreId,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date start,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date end, Integer style, String queryItem, String source, String flowtype,
                                                 int offset, int limit) {
        return balanceService.listBalanceLogs(centreId, getUserTeamId(), start, end, style, queryItem, source, flowtype, offset, limit);
    }


    @RequiresPermissions("flow:balance:gyscwexprot")
    @GetMapping("/gyscwexprot")
    public void gysCwExprot(Long centreId, Date start, Date end, Integer style,
                            String queryItem, String realname, String mobile, String nickname, String flowtype, HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"序号", "结算日期", "姓名", "供应商名称", "订单号", "商品名称", "商品数量", "成本价", "结算金额", "金额变动"};
        resultData.add(0, Arrays.asList(head));
        List<BalanceCWLog> list = balanceService.listAllBalanceLogs(centreId, start, end, style, queryItem, realname, mobile, nickname, flowtype);
        int flag = 1;
        if (CollectionUtils.isNotEmpty(list)) {
            for (BalanceCWLog obj : list) {
                if (obj == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(flag);
                row.add(obj.getJsrq());
                row.add(obj.getGysxm());
                row.add(obj.getGysmc());
                row.add(obj.getDd());
                row.add(obj.getSpmc());
                row.add(obj.getSpsl());
                row.add(obj.getCbj());
                row.add(obj.getJsje());
                row.add(obj.getJsqje() + "->" + obj.getJshje());
                resultData.add(row);
                flag++;
            }
        }
        String fileName = "供应商" + DateUtils.format(start, "yyyyMMddHHmmss") + "至" + DateUtils.format(end, "yyyyMMddHHmmss") + "结算明细";
        try {
            ExcelHelper.exportExcel(response, fileName, "站点预计佣金明细", resultData);
        } catch (IOException e) {
            logger.info("export achieve count error:{}", e.getMessage());
        }
    }


    /**
     * 余额流水导出
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param response
     */
    @RequiresPermissions("flow:balance:export")
    @GetMapping("/export")
    public void exportBalanceLogs(Long centreId, Date start, Date end, Integer style, String queryItem, String source, String flowtype,
                                  HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"流水ID", "昵称", "姓名", "会员ID", "余额", "类型", "改变前余额", "改变后余额", "时间", "备注", "后台操作说明"};
        resultData.add(0, Arrays.asList(head));

        List<BalanceLog> logs = balanceService.listBalanceLogs(centreId, getUserTeamId(), start, end, style, queryItem, source, flowtype);
        if (CollectionUtils.isNotEmpty(logs)) {
            for (BalanceLog bl : logs) {
                if (bl == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(bl.getId());
                row.add(bl.getNickname());
                row.add(bl.getRealname());
                row.add(bl.getMid());
                row.add(bl.getMoney());
                row.add(BalanceLogStyle.get(bl.getStyle()));
                row.add(bl.getBeforeamount());
                row.add(bl.getAfteramount());
                row.add(bl.getCreateTime());
                row.add(bl.getTitle());
                row.add(bl.getRemark());
                resultData.add(row);
            }
        }
        String fileName = "余额流水" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "余额流水", resultData);
        } catch (IOException e) {
            logger.info("export balance log error:{}", e.getMessage());
        }
    }

    /**
     * 根据mid查找对应的余额流水
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("flow:balance:balance")
    @GetMapping("/balanceFlowToMid/{id}")
    public String balanceFlowToMid(@PathVariable String id, Model model) {
        model.addAttribute("mid", id);
        return prefix + "/balanceFlowToMid";
    }

    /**
     * 根据mid查找对应的余额流水列表
     *
     * @param balanceLog
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/listBalanceFlowToMid")
    @RequiresPermissions("flow:balance:balance")
    public PageUtils<BalanceLog> listBalanceFlowToMid(BalanceLog balanceLog, int offset, int limit) {
        return balanceService.listBalanceLogs(balanceLog, offset, limit);
    }


    /**
     * 余额流水页面
     *
     * @param model
     * @return
     */
    @GetMapping("/balanceDetPage")
    @RequiresPermissions("flow:balance:balancedet")
    public String balanceDetPage(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/balancedet";
    }

    /**
     * 余额支付流水明细
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/listBalanceDetLogs")
    @RequiresPermissions("flow:balance:balancedet")
    public PageUtils<BalanceLog> listBalanceDetLogs(Long centreId,String start,String end, Integer style,
                                                    String queryItem, String source, String flowtype,
                                                    int offset, int limit) {
        //类型为余额下单抵扣
        style = 3;
        return balanceService.listBalanceLogs(centreId, getUserTeamId(), DateUtils.parseDateForm(start), DateUtils.parseDateForm(end), style, queryItem, source, flowtype, offset, limit);
    }

    /**
     * 余额支付流水明细总金额统计
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/sumByMoney")
    @RequiresPermissions("flow:balance:balancedet")
    public String sumByMoney(Long centreId,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date start,@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date end, Integer style, String queryItem, String source, String flowtype) {
        //类型为余额下单抵扣
        style = 3;
        return balanceService.sumByMoney(centreId,getUserTeamId(), start, end, style, queryItem, source, flowtype);
    }

    /**
     * 余额流水导出
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @param response
     */
    @RequiresPermissions("flow:balance:export")
    @GetMapping("/exportBalanceDatLogs")
    public void exportBalanceDatLogs(Long centreId, Date start, Date end, Integer style, String queryItem,
                                     HttpServletResponse response) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"流水ID", "昵称", "姓名", "会员ID", "支付金额", "类型", "时间", "备注", "后台操作说明"};
        resultData.add(0, Arrays.asList(head));
        //类型为余额下单抵扣
        style = 3;
        List<BalanceLog> logs = balanceService.listBalanceLogs(centreId,getUserTeamId(), start, end, style, queryItem, null, null);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtils.isNotEmpty(logs)) {
            for (BalanceLog bl : logs) {
                if (bl == null) {
                    continue;
                }
                List<Object> row = new ArrayList<>();
                row.add(bl.getId());
                row.add(bl.getNickname());
                row.add(bl.getRealname());
                row.add(bl.getMid());
                row.add(bl.getMoney());
                row.add("余额支付");
                row.add(DateUtils.format(bl.getCreateTime(), "YYYY:MM:dd HH:mm:ss"));
                try {
                    if (bl.getCreateTime().getTime() <= sdf.parse("2019-04-16 20:00:00").getTime()) {
                        row.add("站点充值");
                    } else {
                        row.add("下单抵扣");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                row.add(bl.getRemark());
                resultData.add(row);
            }
        }
        String fileName = "余额流水" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
        try {
            ExcelHelper.exportExcel(response, fileName, "余额流水", resultData);
        } catch (IOException e) {
            logger.info("export balance log error:{}", e.getMessage());
        }
    }
}
